package com.xiaoma.tpo.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xiaoma.tpo.dao.TRoleDao;
import com.xiaoma.tpo.dao.TRoleRightDao;
import com.xiaoma.tpo.dao.TUserRoleDao;
import com.xiaoma.tpo.domain.TRole;
import com.xiaoma.tpo.domain.TUserRole;
import com.xiaoma.tpo.dto.TRoleVO;

@Service
public class TRoleService {
	@Autowired
	private TRoleDao roleDao;
	@Autowired
	private TUserRoleDao tUserRoleDao;
	
	@Autowired
	private TRoleRightDao tRoleRightDao;
	
	public List<TRole> findAllRoles(){
		List<TRole> rTRoles = roleDao.findAllRoles();
		return rTRoles;
	}

	public void save(TRole role) {
		role.setGenTime(new Date());
		role.setUpdateTime(new Date());
		roleDao.insert(role);
	}

	public void edit(TRole role) {
		role.setUpdateTime(new Date());
		roleDao.update(role);
		
	}

	public void delete(Integer id) {
		roleDao.delete(id);
		
	}

	public List<TRoleVO> findAllRole() {
		List<TRole> rTRoles = roleDao.findAllRoles();
		List<TRoleVO> roleVOs =new ArrayList<TRoleVO>();
		for(TRole tRole:rTRoles){
			TRoleVO tRoleVO = new TRoleVO();
			tRoleVO.setId(tRole.getId());
			tRoleVO.setName(tRole.getRoleName());
			roleVOs.add(tRoleVO);
		}
		return roleVOs;
	}
	//验证角色 添加/修改时 不能重复
	public boolean validateRole(TRole role,Integer mark) {
		if(mark ==2){
			List<TRole> tRoles = roleDao.findByRoleName(role);
			if(tRoles != null && tRoles.size() >0){
				if(tRoles.get(0).getId() != role.getId()){
					return true;
				}else{
					return false;
				}
			}
			return false;
			
		}
		List<TRole> tRoles = roleDao.findByRoleName(role);
		if(tRoles!=null && tRoles.size()>0){
			return true;
		}
		return false;
	}

	public boolean hasRelation(Integer roleId) {
		TUserRole tUserRole = new TUserRole();
		tUserRole.setRoleId(roleId);
		List<TUserRole> rTUserRoles = tUserRoleDao.findByColumns(tUserRole);
		if(rTUserRoles != null && rTUserRoles.size()>0){
			return true;
		}
		return false;
	}
	//根据角色roleId删除 t_role_right 的关系
	public void deleteRelation(Integer userId) {
		tRoleRightDao.deleteBefore(userId);
		
	}

	

}
